<template>
  <div class="rolesBox">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主体部分卡片 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-button
        type="primary"
        style="margin-left: 0px; margin-bottom: 15px"
        @click="dialogFormVisible = true"
        >添加角色</el-button
      >
      <!-- 主体表格部分 -->
      <el-table border class="mt-15" :data="roleData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row v-for="(first, i) in props.row.children" :key="i">
              <el-col :span="4" class="line">
                <el-tag
                  closable
                  effect="dark"
                  @close="handleClose(first, props.row)"
                  >{{ first.authName }}</el-tag
                >
                <i class="el-icon-caret-right" v-if="first.children"></i>
              </el-col>
              <el-col :span="20">
                <el-row v-for="(second, j) in first.children" :key="j">
                  <el-col :span="6" class="line">
                    <el-tag
                      closable
                      effect="dark"
                       type="success"
                      @close="handleClose(second, props.row)"
                      >{{ second.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right" v-if="second.children"></i>
                  </el-col>
                  <el-col :span="18" class="line">
                    <el-tag
                      closable
                      effect="dark"
                      type="warning"
                      v-for="(third, k) in second.children"
                      :key="k"
                      @close="handleClose(third, props.row)"
                      >{{ third.authName }}
                      <i class="el-icon-caret-right" v-if="third.children"></i>
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <el-row v-if="props.row.children.length === 0">
              <el-col :span="24">该角色没有分配权限，请前往分配！</el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" prop="id" width="48px" align="center">
        </el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
          min-width="360"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="描述"
          prop="roleDesc"
          min-width="360"
          align="center"
        >
        </el-table-column>
        <el-table-column label="操作" min-width="360" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              dark
              icon="el-icon-edit"
              @click="editRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              dark
              icon="el-icon-delete"
              @click="deleteRole(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              dark
              icon="el-icon-check"
              title="授权角色"
              @click="allocatedRights(scope.$index, scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form" :rules="rules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editVisible">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="editForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesData">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色授权弹框 -->
    <el-dialog title="分配权限" :visible.sync="roleRightVisible">
      <el-tree
        ref="tree"
        default-expand-all
        :data="rightsData"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectedRights"
        :props="defaultProps"
        @check-change='selectCheckedEvent'
      >
      </el-tree>

      <div slot="footer" class="dialog-footer">
        <el-button @click="roleRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEmpower">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAddRoles,
  getRoles,
  getUpdateRoles,
  getDeleteRole,
  getDeleteRolesRights,
  getRights,
  getRolesRights
} from "../../api/index";

export default {
  data() {
    return {
      roleData: [],
      rightsData: [],
      form: {
        roleName: "",
        roleDesc: "",
      },
      formLabelWidth: "200px",
      dialogFormVisible: false,
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      editRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      editVisible: false,
      editForm: [],
      roleRightVisible: false,
      defaultProps: {
          children: 'children',
          label: 'authName'
        },
      selectedRights: [],
      roleId: '',
      rids: '',  //权限 ID 列表（字符串）
    };
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      let { data: data } = await getRoles(this.params);
      // console.log(data);
      this.roleData = data;
    },
    async addRoles() {
      let {
        meta: { msg, status },
      } = await getAddRoles(this.form);
      if (status == 201) {
        // 添加数据信息成功则弹出提示信息并隐藏对话框
        this.$message.success(msg);
        this.dialogFormVisible = false;
        // 重新渲染页面
        this.getRolesList();
      } else {
        this.$message.error(msg);
      }
    },
    editRole(data) {
      this.editVisible = true;
      this.editForm = data;
    },
    // 修改信息提交
    async editRolesData() {
      let success = await this.$refs["editForm"].validate().catch(() => {});
      if (!success) return false;

      let {
        meta: { msg, status },
      } = await getUpdateRoles(this.editForm);
      if (status == 200) {
        this.$message.success(msg);
        this.editVisible = false;
        this.getRolesList();
      } else {
        this.$message.error(msg);
      }
    },
    async deleteRole(data) {
      let res = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});

      if (res != "confirm") return this.$message("取消操作");

      let {
        meta: { msg, status },
      } = await getDeleteRole(data.id);
      if (status == 200) {
        this.$message.success(msg);
        this.getRolesList();
      } else {
        this.$message(msg);
      }
    },
    async handleClose(tag, scopeRow) {
      let res = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {});

      if (res != "confirm") return this.$message("取消操作");
      let {
        data,
        meta: { status },
      } = await getDeleteRolesRights({ roleId: scopeRow.id, rightId: tag.id });

      if (status != 200) return this.$message.error(msg);

      // 怎么实现删除指定权限后页面局部刷新???
      scopeRow.children = data
    },
    async allocatedRights(i, scopeRow) {
      this.selectedRights = []
      this.roleRightVisible = true;
      let { data, meta: {msg, status} } = await getRights({ type: 'tree' })
      if(status != 200) return this.$message.error(msg)
      this.rightsData = data;
      this.roleId = scopeRow.id
      // 显示当前已拥有的权限
      this.checkedNodeId(scopeRow, this.selectedRights)
    },
    // 利用递归逐层获取当前分支被选中的最后一级
    checkedNodeId(scopedRowNode, selectedRightsArr) {
      // 没有children时表示是最后一个节点.此时存储对应id
      if(!scopedRowNode.children) {
        return selectedRightsArr.push(scopedRowNode.id);
      }

      scopedRowNode.children.forEach((item) => {
        return this.checkedNodeId(item, selectedRightsArr)
      })
    },
    // 根据elementui提供的函数获取每一次节点被选中状态改变的数据
    selectCheckedEvent() {
      let checkedKeys = this.$refs.tree.getCheckedKeys()
      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      let arr = [...checkedKeys,...halfCheckedKeys];
      this.rids = arr.join()
    },
    // 提交重新授权的权限列表
    async submitEmpower() {
      // console.log(this.roleId);
      let { data,meta: {msg, status} } = await getRolesRights({roleId: this.roleId, rids: this.rids})
      // console.log(status, data);
      if(status != 200) return this.$message.error(msg)
      this.roleRightVisible = false;
      this.$message.success(msg)
      // 初始化权限数据
      this.getRolesList()
    }
  },
  created() {
    this.getRolesList();
  },
};
</script>

<style scoped>
.box-card {
  width: 100%;
  max-height: 800px;
  overflow: auto;
  text-align: left;
}

.rolesBox {
  padding-left: 20px;
}

.el-breadcrumb {
  font-size: 12px;
  background-color: initial;
  margin-bottom: 0;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.el-table_1_column_2 {
  width: 48px;
}

.el-dialog {
  text-align: center;
}
.el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.el-row {
  padding-left: 20px;
}
</style>
